<?php
/* 
 * This model handels all information regarding the interests
 */

/**
 * @author ChristianNotebook
 */
class Model_interests extends CI_Model
{
    function  __construct()
    {
        parent::__construct();
    }

    // adds a new interest to interests
    function addNewInterestToInterests()
    {
        $newInterestToInterests = array(
          'interestName' => $_POST['interestName']
        );
        $this->db->insert('interests', $newInterestToInterests);
    }

    // adds a new interest to the user that is logged in.
    function addNewInterestToUser($interestId)
    {
        $userid = $this->session->userdata('id');
        $newInterestToUser = array(
            'userid' => $userid,
            'interest_id' => $interestId
        );
        $this->db->insert('user_interests', $newInterestToUser);
        //error_log(print_r($newInterestToUser));
    }

    // returns all of the interest in an array.
    function listAllInterests()
    {
        $data = array();
        $this->db->order_by('interestName','asc');
        $Q = $this->db->get('interests');

        if ($Q->num_rows() > 0)
        {
            foreach ($Q->result_array() as $row)
            {
                $data[] = $row;
            }
        }
        $Q->free_result();
        return $data;
    }

    // lists all of a users interests it uses the interestsbyuser view from the db
    function listInterestsByUser()
    {
        $userid = $this->session->userdata('id');
        $this->db->where('userid', $userid);

        $Q = $this->db->get('interestsbyuser');
        if ($Q->num_rows() > 0)
        {
            foreach ($Q->result_array() as $row)
            {
                $data[] = $row;
                //error_log(print_r($data, true));
            }
        }
        else
        {
            $data = array();
        }
        $Q->free_result();
        return $data;
        
    }

    // lists all users that have a specific interest, by selecting userid from
    // the interestsbyuser table and getting a user from the user table.
    function listUsersByInterest($interest_id)
    {

        $sql = "SELECT * FROM user WHERE id in (SELECT userid FROM interestsbyuser WHERE interest_id = $interest_id)";
        
        $Q = $this->db->query($sql);
        
        if ($Q->num_rows() > 0)
        {
            foreach ($Q->result() as $row)
            {
                $data[] = $row;
            }
        }
        else
        {
            $data = array();
        }
        $Q->free_result();
        return $data;
    }

    // gets an interest by the interest id. 
    function getInterestsById($id)
    {
        $data = array();
        $options = array('id' => $id);
        $Q = $this->db->getwhere('interests', $options,1);

        if ($Q->num_row() > 0)
        {
            $data = $Q->row_array();
        }

        $Q->free_results();
        return $data;
    }
}
?>
